package org.csu.chatserver.coder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.FileRegion;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.stream.ChunkedFile;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.util.List;

public class WebSocketFrameEncoder extends MessageToMessageEncoder<FileRegion> {

    @Override
    protected void encode(ChannelHandlerContext ctx, FileRegion region, List<Object> out) throws Exception {
        // 处理 FileRegion（零拷贝文件传输）
        ByteBuf buffer = ctx.alloc().buffer((int) region.count());
        region.transferTo(new ByteBufWritableChannel(buffer), region.transferred());
        out.add(new BinaryWebSocketFrame(buffer));
    }

    // 自定义 WritableByteChannel 适配器
    private static class ByteBufWritableChannel implements WritableByteChannel {
        private final ByteBuf buffer;

        public ByteBufWritableChannel(ByteBuf buffer) {
            this.buffer = buffer;
        }

        @Override
        public int write(ByteBuffer src) {
            int length = src.remaining();
            buffer.writeBytes(src);
            return length;
        }

        @Override
        public boolean isOpen() {
            return true;
        }

        @Override
        public void close() {
            // 无需关闭
        }
    }
}

